class Import
	def self.import

  #docs是文档前面的编号和model的映射关系
  #table_head是文档对应的这个文档里字段的顺序，依照从左往右的顺序，table_head方法后面的数字表示年份，表示在这个年份里model对应的文档的字段顺序，
  #因为每个年份相同的model对应的文档字段可能不一样才这样处理

	docs = 		{"B65" => ScienceAchievement, "B58" => ManPower, "B61" => ResearchDevelopment, "B66" => Assignment, \
			"B60" => ScienceFund, "B59" => ManDuty, "B63" => Communication, "B64" => Award, "B62" => AchievementService}

  numbers = ["B65", "B58", "B61", "B66", "B60", "B59", "B63", "B64", "B62"]


  (2005...2016).each do |year|
    puts "开始导入#{year}年"

  	Dir.glob("#{Rails.root}/docs/#{year}/*.xls").select {|xls| numbers.include?(xls[/B(\d)+/]) }.sort.each do |path|
      ss = Roo::Excel.new(path)
  		ss.sheets.each do |s|
  		  ss.default_sheet = s
        ((ss.first_row+1)..ss.last_row).each do |i|
          #这里正则是用来匹配从左往右数第一个字段是否包括大学或者学院，这样处理的话即使文档行数不确定也不会出错
  		  	if ss.cell(i,1) && ss.cell(i,1) =~ /(大学|学院)/
  			  	hash = {}
  			    begin
  			    	school = School.find_or_create_by(name: ss.cell(i,1).to_s.strip)

  			      model = docs[path[/B(\d)+/]]
  			      model.table_head[year.to_s].each_with_index do |k,index|
  			      	hash[k] = ss.cell(i,index+2).to_i
  			      end
  			      hash[:school_id] = school.id
  			      hash[:record_year] = year
  			      model.create(hash)
  			      # SchoolTag.create(school_id: school.id,)
  			    rescue Exception=>e
  			      p e
  			    end
  			  else
  			  	next
  			  end
  		  end
  		end
    end

    puts "#{year}年导入完毕"
  end
  end
end
